/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package genomemap.stat;

import JSci.maths.statistics.ChiSqrDistribution;

import javautil.io.LogUtil;
import javautil.lang.MathUtil;

/**
 * Class description
 *
 * @version        Enter version here..., 12/11/23
 * @author         Susanta Tewari
 */
public class PValue {

    /**
     * <CODE>cProb</CODE>: estimated or parameter <CODE>c</CODE> (probability of exachange) estimates.
     * <CODE>order</CODE>: the gene order to be used
     * <CODE>array</CODE>: the genotype of genes for the gene order <CODE>order</CODE>.
     * The array must not contain any missing values.
     */
    public static double getPValue(double[] cProb, int[] order, int[][] array, boolean verbose)
            throws Exception {


        // obsFreq has observed recombinant counts for each genetic interval
        int total_obs      = array[0].length;
        int[][] obsFreq    = new int[order.length - 1][4];
        double[][] expFreq = new double[order.length - 1][4];
        int count1         = 0,
            count2         = 0,
            count3         = 0,
            count4         = 0;

        for (int i = 1; i < order.length; i++) {

            for (int index = 0; index < total_obs; index++) {

                if (((array[i - 1][index] == 1) && (array[i][index] == 1))) {
                    count1++;
                }

                if (((array[i - 1][index] == 1) && (array[i][index] == 0))) {
                    count2++;
                }

                if (((array[i - 1][index] == 0) && (array[i][index] == 1))) {
                    count3++;
                }

                if (((array[i - 1][index] == 0) && (array[i][index] == 0))) {
                    count4++;
                }
            }

            obsFreq[i - 1][0] = count1;
            obsFreq[i - 1][1] = count2;
            obsFreq[i - 1][2] = count3;
            obsFreq[i - 1][3] = count4;
            count1            = 0;
            count2            = 0;
            count3            = 0;
            count4            = 0;
        }

        /**
         * CALCULATE THE EXPECTED COUNTS FOR EACH GENETIC INTERVAL
         */
        for (int i = 0; i < order.length - 1; i++) {

            double c1ClassProb = getc1ClassProb(i + 1, cProb);

            if ((c1ClassProb > 1) || (c1ClassProb < 0)) {

                System.out.println("The probability is out of range ... exiting...");
                System.exit(0);
            }

            expFreq[i][0] = (double) total_obs
                            * (c1ClassProb * (Math.pow(cProb[i], 2.0) - 2.0 * cProb[i] + 2.0) / 4.0
                               + (1 - c1ClassProb)
                                 * (Math.pow(cProb[i], 2.0) - 4.0 * cProb[i] + 8.0) / 16.0);
            expFreq[i][1] = (double) total_obs
                            * (c1ClassProb * (2 * cProb[i] - Math.pow(cProb[i], 2.0)) / 4.0
                               + (1 - c1ClassProb) * (4 * cProb[i] - Math.pow(cProb[i], 2.0))
                                 / 16.0);
            expFreq[i][2] = (double) total_obs
                            * (c1ClassProb * (2 * cProb[i] - Math.pow(cProb[i], 2.0)) / 4.0
                               + (1 - c1ClassProb) * (4 * cProb[i] - Math.pow(cProb[i], 2.0))
                                 / 16.0);
            expFreq[i][3] = (double) total_obs
                            * (c1ClassProb * (Math.pow(cProb[i], 2.0) - 2.0 * cProb[i] + 2.0) / 4.0
                               + (1 - c1ClassProb)
                                 * (Math.pow(cProb[i], 2.0) - 4.0 * cProb[i] + 8.0) / 16.0);

            if (verbose) System.out.println("total_obs is :" + total_obs);
            if (verbose) System.out.println("exp Freq is :" + MathUtil.Sum(expFreq[i]));
        }


        // Calculate the Chi-Square and find its p-value
        double pValue    = -1.0;
        double chiSquare = 0.0;

        for (int index = 0; index < obsFreq.length; index++) {

            for (int i = 0; i < 4; i++) {

                if (expFreq[index][i] == 0) {
                    expFreq[index][i] = 0.00001;
                }

                chiSquare += Math.pow(obsFreq[index][i] - expFreq[index][i], 2.0)
                             / expFreq[index][i];
            }
        }

        ChiSqrDistribution chiDist = new ChiSqrDistribution(2.0 * obsFreq.length);

        if (verbose) System.out.println("Chi Square is : " + chiSquare);

        pValue = 1.0 - new ChiSqrDistribution(2.0 * obsFreq.length).cumulative(chiSquare);

        if (verbose) {

            System.out.println("Obs freq: ");
            LogUtil.print(obsFreq);
            System.out.println("Exp freq: ");
            LogUtil.print(expFreq);
            System.out.println(" The chiSquare value is : " + chiSquare + " with df "
                               + 2 * obsFreq.length);
            System.out.println(" The p value is : " + pValue);
        }

        if (!((pValue > 0.0) && (pValue < 1.0))) throw new Exception("P-Value Computation failed");

        return pValue;
    }

    /**
     * Method description
     *
     * @param i description
     * @param cProb description
     *
     * @return description
     */
    private static double getc1ClassProb(int i, double[] cProb) {


        // i is genetic interval number not ist`s array index
        double[] pProbOld = new double[6];
        double[] pProbNew = new double[6];


        // Initialize for 0th generation.
        pProbOld[0] = Math.pow(1 - cProb[0], 2.0) + Math.pow(cProb[0], 2.0) / 4.0;

        for (int index = 1; index < 5; index++) {

            pProbOld[index] = cProb[0] * (1 - cProb[0]) / 2.0 + Math.pow(cProb[0], 2.0) / 8.0;
        }

        pProbOld[5] = Math.pow(cProb[0], 2.0) / 4.0;

        for (int index1 = 1; index1 < i; index1++) {


            // print(pProbOld);
            // System.out.println(" The prob MyUtility.Sum is : "+MyUtility.Sum(pProbOld));
            double c = cProb[index1];

            pProbNew[0] = (Math.pow(1 - c, 2.0) + Math.pow(c, 2.0) / 4.0) * pProbOld[0]
                          + (c * (1 - c) / 2 + Math.pow(c, 2.0) / 8.0)
                            * (pProbOld[1] + pProbOld[2] + pProbOld[3] + pProbOld[4]) + Math.pow(c,
                                2.0) / 4.0 * pProbOld[5];
            pProbNew[1] =
                (c * (1 - c) / 2 + Math.pow(c, 2.0) / 8.0) * (pProbOld[0] + pProbOld[5])
                + (Math.pow(1 - c, 2.0) + c * (1 - c) + 3.0 / 8 * Math.pow(c, 2.0)) * pProbOld[1]
                + Math.pow(c, 2.0) / 16 * (3.0 * pProbOld[2] + 2.0 * pProbOld[3] + pProbOld[4]);
            pProbNew[2] = (c * (1 - c) / 2 + Math.pow(c, 2.0) / 8.0) * (pProbOld[0] + pProbOld[5])
                          + Math.pow(c, 2.0) / 8.0 * (pProbOld[1] + pProbOld[3] + pProbOld[4])
                          + (Math.pow(1 - c, 2.0) + c * (1 - c) + 3.0 / 8 * Math.pow(c, 2.0))
                            * pProbOld[2];
            pProbNew[3] = (c * (1 - c) / 2 + Math.pow(c, 2.0) / 8.0) * (pProbOld[0] + pProbOld[5])
                          + Math.pow(c, 2.0) / 16
                            * (2.0 * pProbOld[1] + pProbOld[2]
                               + 3.0 * pProbOld[4]) + (Math.pow(1 - c, 2.0) + c * (1 - c)
                                   + 3.0 / 8 * Math.pow(c, 2.0)) * pProbOld[3];
            pProbNew[4] = (c * (1 - c) / 2 + Math.pow(c, 2.0) / 8.0) * (pProbOld[0] + pProbOld[5])
                          + Math.pow(c, 2.0) / 8 * (pProbOld[1] + pProbOld[2] + pProbOld[3])
                          + (Math.pow(1 - c, 2.0) + c * (1 - c) + 3.0 / 8.0 * Math.pow(c, 2.0))
                            * pProbOld[4];
            pProbNew[5] =
                Math.pow(c, 2.0) / 4 * pProbOld[0]
                + (c * (1 - c) / 2 + Math.pow(c, 2.0) / 8.0)
                  * (pProbOld[1] + pProbOld[2] + pProbOld[3] + pProbOld[4]) + (Math.pow(1 - c, 2.0)
                     + Math.pow(c, 2.0) / 4.0) * pProbOld[5];
            pProbOld = pProbNew.clone();
        }

        return (pProbOld[0] + pProbOld[5]);
    }
}
